<template>
  <view class="goods-detail-container">
    <!-- 商品图片轮播 -->
    <swiper class="goods-swiper" indicator-dots autoplay circular indicator-color="#E5E6EB" indicator-active-color="#FF6B00">
      <swiper-item v-for="(image, index) in goodsDetail.images" :key="index">
        <image :src="image" class="goods-image" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <!-- 商品信息 -->
    <view class="goods-info">
      <view class="price-section">
        <view class="price-row">
          <text class="current-price">¥{{ goodsDetail.price }}</text>
          <text class="original-price" v-if="goodsDetail.original_price">¥{{ goodsDetail.original_price }}</text>
          <view class="seckill-tag" v-if="goodsDetail.is_seckill">
            <text>限时秒杀</text>
          </view>
        </view>
        <view class="seckill-info" v-if="goodsDetail.is_seckill">
          <text class="seckill-price">秒杀价：¥{{ goodsDetail.seckill_price }}</text>
          <uv-count-down :timestamp="seckillEndTime" format="HH:mm:ss"></uv-count-down>
        </view>
      </view>
      
      <view class="goods-title">
        <text>{{ goodsDetail.name }}</text>
      </view>
      
      <view class="goods-desc">
        <text>{{ goodsDetail.description }}</text>
      </view>
      
      <view class="sales-info">
        <text>已售 {{ goodsDetail.sold_count }} 件</text>
        <text>库存 {{ goodsDetail.stock }} 件</text>
      </view>
    </view>

    <!-- 团长信息 -->
    <view class="leader-section" v-if="goodsDetail.leader" @click="goToLeaderDetail(goodsDetail.leader.id)">
      <view class="leader-info">
        <image :src="goodsDetail.leader.avatar" class="leader-avatar" mode="aspectFill"></image>
        <view class="leader-detail">
          <text class="leader-name">{{ goodsDetail.leader.name }}</text>
          <text class="store-name">{{ goodsDetail.leader.store_name }}</text>
          <text class="service-radius">服务半径 {{ goodsDetail.leader.service_radius }}m</text>
        </view>
      </view>
      <view class="leader-commission">
        <text class="commission-text">佣金 {{ goodsDetail.leader.commission_rate }}%</text>
        <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="spec-section" v-if="goodsDetail.specifications">
      <view class="spec-item" v-for="spec in goodsDetail.specifications" :key="spec.name">
        <text class="spec-name">{{ spec.name }}</text>
        <view class="spec-values">
          <text 
            class="spec-value" 
            v-for="value in spec.values" 
            :key="value"
            :class="{ active: selectedSpecs[spec.name] === value }"
            @click="selectSpec(spec.name, value)"
          >
            {{ value }}
          </text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">
        <text>商品详情</text>
      </view>
      <view class="detail-content">
        <text>{{ goodsDetail.description }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="left-actions">
        <view class="action-item" @click="goToCart">
          <uv-icon name="shopping-cart" size="24" color="#666"></uv-icon>
          <text class="action-text">购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
        </view>
        <view class="action-item" @click="toggleFavorite">
          <uv-icon :name="isFavorite ? 'heart-fill' : 'heart'" size="24" :color="isFavorite ? '#ff4444' : '#666'"></uv-icon>
          <text class="action-text">收藏</text>
        </view>
        <view class="action-item" @click="goToLeaderDetail(goodsDetail.leader?.id)">
          <uv-icon name="account" size="24" color="#666"></uv-icon>
          <text class="action-text">团长</text>
        </view>
      </view>
      <view class="right-actions">
        <button class="add-cart-btn" @click="addToCart">加入购物车</button>
        <button class="buy-now-btn" @click="buyNow">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <uv-popup ref="specPopup" type="bottom">
      <view class="spec-popup">
        <view class="popup-header">
          <text class="popup-title">选择规格</text>
          <uv-icon name="close" size="20" color="#999" @click="closeSpecPopup"></uv-icon>
        </view>
        <view class="popup-content">
          <view class="goods-preview">
            <image :src="goodsDetail.images?.[0]" class="preview-image" mode="aspectFill"></image>
            <view class="preview-info">
              <text class="preview-price">¥{{ currentPrice }}</text>
              <text class="preview-stock">库存：{{ goodsDetail.stock }}件</text>
            </view>
          </view>
          
          <view class="spec-selection" v-if="goodsDetail.specifications">
            <view class="spec-item" v-for="spec in goodsDetail.specifications" :key="spec.name">
              <text class="spec-name">{{ spec.name }}</text>
              <view class="spec-values">
                <text 
                  class="spec-value" 
                  v-for="value in spec.values" 
                  :key="value"
                  :class="{ active: selectedSpecs[spec.name] === value }"
                  @click="selectSpec(spec.name, value)"
                >
                  {{ value }}
                </text>
              </view>
            </view>
          </view>
          
          <view class="quantity-section">
            <text class="quantity-label">数量</text>
            <uv-number-box v-model="quantity" min="1" :max="goodsDetail.stock"></uv-number-box>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmSelection">确定</button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
// 使用 Vue3 <script setup> 语法重构（中文注释，变量/函数使用英文）
import { ref, reactive, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { goodsApi, cartApi } from '../../api/index.js'

// 全局方法（如 $navigateTo/$showToast）
const { proxy } = getCurrentInstance()

// 模板 ref
const specPopup = ref(null)

// 状态
const goodsId = ref('')
const goodsDetail = reactive({})
const selectedSpecs = reactive({})
const quantity = ref(1)
const isFavorite = ref(false)
const cartCount = ref(0)
const seckillEndTime = ref(0)
const currentPrice = ref(0)

// 初始化页面
const initPage = async () => {
  uni.showLoading({ title: '加载中...' })
  try {
    const data = await goodsApi.getGoodsDetail(goodsId.value)
    // 覆盖响应式对象字段
    Object.keys(goodsDetail).forEach(k => delete goodsDetail[k])
    Object.assign(goodsDetail, data || {})
    currentPrice.value = data.is_seckill ? data.seckill_price : data.price

    if (data.is_seckill && data.seckill_end_time) {
      seckillEndTime.value = new Date(data.seckill_end_time).getTime()
    }

    // 初始化规格选择
    Object.keys(selectedSpecs).forEach(k => delete selectedSpecs[k])
    if (data.specifications) {
      data.specifications.forEach(spec => {
        selectedSpecs[spec.name] = spec.values[0]
      })
    }

    await getCartCount()
  } catch (error) {
    proxy?.$showToast?.('加载失败')
  } finally {
    uni.hideLoading()
  }
}

// 选择规格
const selectSpec = (specName, value) => {
  selectedSpecs[specName] = value
}

// 获取购物车数量
const getCartCount = async () => {
  try {
    const cartList = await cartApi.getCartList()
    cartCount.value = cartList.length
  } catch (error) {
    console.error('获取购物车数量失败', error)
  }
}

// 添加到购物车
const addToCart = () => {
  if (!checkSpecSelected()) return
  specPopup.value?.open()
}

// 立即购买
const buyNow = () => {
  if (!checkSpecSelected()) return
  specPopup.value?.open()
}

// 检查规格是否已选择
const checkSpecSelected = () => {
  if (!goodsDetail.specifications) return true
  const requiredSpecs = goodsDetail.specifications.length
  const selectedCount = Object.keys(selectedSpecs).length
  if (selectedCount < requiredSpecs) {
    proxy?.$showToast?.('请选择商品规格')
    return false
  }
  return true
}

// 确认选择
const confirmSelection = async () => {
  const cartData = {
    goods_id: goodsId.value,
    quantity: quantity.value,
    specifications: selectedSpecs
  }
  try {
    await cartApi.addToCart(cartData)
    proxy?.$showToast?.('添加成功')
    getCartCount()
    specPopup.value?.close()
  } catch (error) {
    proxy?.$showToast?.('添加失败')
  }
}

// 关闭规格弹窗
const closeSpecPopup = () => {
  specPopup.value?.close()
}

// 切换收藏
const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value
  proxy?.$showToast?.(isFavorite.value ? '已收藏' : '已取消收藏')
}

// 跳转购物车
const goToCart = () => {
  uni.switchTab({ url: '/pages/cart/index' })
}

// 跳转团长详情
const goToLeaderDetail = (leaderId) => {
  if (leaderId) {
    proxy?.$navigateTo?.(`/pages/leader/detail?id=${leaderId}`)
  }
}

// 生命周期
onLoad((options) => {
  goodsId.value = options?.id || ''
  initPage()
})
</script>

<style lang="scss" scoped>
.goods-detail-container {
  min-height: 100vh;
  background-color: $uni-bg-color-grey;
  padding-bottom: 120rpx;
}

.goods-swiper {
  height: 750rpx;
  margin-bottom: 20rpx;
  
  .goods-image {
    width: 100%;
    height: 100%;
  }
}

.goods-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  
  .price-section {
    margin-bottom: 20rpx;
    
    .price-row {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      
      .current-price {
        font-size: 40rpx;
        color: $uni-color-primary;
        font-weight: bold;
        margin-right: 20rpx;
      }
      
      .original-price {
        font-size: 28rpx;
        color: #999;
        text-decoration: line-through;
        margin-right: 20rpx;
      }
      
      .seckill-tag {
        background-color: $uni-color-primary;
        color: #fff;
        font-size: 22rpx;
        padding: 4rpx 12rpx;
        border-radius: 10rpx;
      }
    }
    
    .seckill-info {
      display: flex;
      align-items: center;
      
      .seckill-price {
        font-size: 28rpx;
        color: $uni-color-primary;
        margin-right: 20rpx;
      }
    }
  }
  
  .goods-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 15rpx;
  }
  
  .goods-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
    margin-bottom: 20rpx;
  }
  
  .sales-info {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;
    color: #999;
  }
}

.leader-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .leader-info {
    display: flex;
    align-items: center;
    
    .leader-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
    
    .leader-detail {
      .leader-name {
        font-size: 30rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 5rpx;
      }
      
      .store-name {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 5rpx;
      }
      
      .service-radius {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
  
  .leader-commission {
    display: flex;
    align-items: center;
    
    .commission-text {
      font-size: 26rpx;
      color: $uni-color-primary;
      margin-right: 10rpx;
    }
  }
}

.spec-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  
  .spec-item {
    margin-bottom: 30rpx;
    
    .spec-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .spec-values {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      
      .spec-value {
        padding: 15rpx 30rpx;
        border: 2rpx solid $uni-border-color;
        border-radius: 25rpx;
        font-size: 26rpx;
        color: #666;
        
        &.active {
          border-color: $uni-color-primary;
          color: $uni-color-primary;
          background-color: #fff5e6;
        }
      }
    }
  }
}

.detail-section {
  background-color: #fff;
  padding: 30rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  
  .section-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  
  .detail-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  border-top: 1rpx solid $uni-border-color;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -6rpx 18rpx rgba(0,0,0,0.06);
  
  .left-actions {
    display: flex;
    align-items: center;
    
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 40rpx;
      position: relative;
      
      .action-text {
        font-size: 20rpx;
        color: #666;
        margin-top: 5rpx;
      }
      
      .cart-badge {
        position: absolute;
        top: -5rpx;
        right: -10rpx;
        background-color: $uni-color-primary;
        color: #fff;
        font-size: 20rpx;
        padding: 2rpx 8rpx;
        border-radius: 10rpx;
        min-width: 30rpx;
        text-align: center;
      }
    }
  }
  
  .right-actions {
    flex: 1;
    display: flex;
    gap: 20rpx;
    
    .add-cart-btn, .buy-now-btn {
      flex: 1;
      height: 70rpx;
      border-radius: 35rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .add-cart-btn {
      background-color: #fff5e6;
      color: $uni-color-primary;
    }
    
    .buy-now-btn {
      background-color: $uni-color-primary;
      color: #fff;
    }
  }
}

.spec-popup {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid $uni-border-color;
    
    .popup-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .popup-content {
    padding: 30rpx;
    
    .goods-preview {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .preview-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
      }
      
      .preview-info {
        .preview-price {
          font-size: 32rpx;
          color: $uni-color-primary;
          font-weight: bold;
          margin-bottom: 10rpx;
        }
        
        .preview-stock {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .spec-selection {
      margin-bottom: 30rpx;
      
      .spec-item {
        margin-bottom: 30rpx;
        
        .spec-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 20rpx;
        }
        
        .spec-values {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;
          
          .spec-value {
            padding: 15rpx 30rpx;
            border: 2rpx solid $uni-border-color;
            border-radius: 25rpx;
            font-size: 26rpx;
            color: #666;
            
            &.active {
              border-color: $uni-color-primary;
              color: $uni-color-primary;
              background-color: #fff5e6;
            }
          }
        }
      }
    }
    
    .quantity-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .quantity-label {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
  
  .popup-footer {
    padding: 30rpx;
    border-top: 1rpx solid $uni-border-color;
    
    .confirm-btn {
      width: 100%;
      height: 80rpx;
      background-color: $uni-color-primary;
      color: #fff;
      border-radius: 40rpx;
      font-size: 30rpx;
      border: none;
    }
  }
}
</style> 